package com.itboye.sunsun.login.ui;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.json.JSONException;
import org.json.JSONObject;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

import com.google.gson.Gson;
import com.itboye.homesensen.alert.ByAlert;
import com.itboye.sunsunhome.R;
import com.itboye.sunsunhome.bean.AdBean;
import com.itboye.sunsunhome.util.XImageLoader;
import com.itboye.sunsunhome.www.aq.DeviceActivity;
import com.itboye.sunsunhome.www.aq.base.MyApplication;
import com.itboye.sunsunhome.wxapi.WXEntryActivity;
import com.itboye.sunsun.application.App;
import com.itboye.sunsun.beans.PersonDataBean;
import com.itboye.sunsun.constants.SPContants;
import com.itboye.sunsun.controller.LoginController;
import com.itboye.sunsun.controller.LoginedState;
import com.itboye.sunsun.network.HttpRequest;
import com.itboye.sunsun.support.BaseActivity;
import com.itboye.sunsun.utils.DebugLog;
import com.itboye.sunsun.utils.SPUtils;
import com.itboye.sunsun.volley.CodeErrorException;
import com.itboye.sunsun.volley.MyJsonRequest;
import com.itboye.sunsun.volley.XErrorListener;
import com.itboye.sunsun.volley.XRequestListener;
import com.tencent.connect.common.Constants;
import com.tencent.mm.sdk.modelmsg.SendAuth;
import com.tencent.mm.sdk.openapi.IWXAPI;
import com.tencent.mm.sdk.openapi.WXAPIFactory;
import com.tencent.tauth.IUiListener;
import com.tencent.tauth.Tencent;
import com.tencent.tauth.UiError;

/**
 * 
 * @author
 * 
 */
public class LoginActivity extends BaseActivity implements OnClickListener,
		IUiListener {

	private Button login;
	private Button wechat;
	private Button forgetpassword;
	private Button smslogin;
	private Button regist;
	private EditText phoneedit;
	private EditText passwordedit;
	private String phone;
	private String password;
	private static final String APP_ID = "wxabf9bc3a048000ac";
	private IWXAPI api;
	public static String LOGINEXIT = "com.itboye.sunsun.exit";

	private Button btn_qqwechat;
	private Tencent mTencent;
	String scope;
	String openid = "";
	String token = "";
	String code;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub

		super.onCreate(savedInstanceState);
		api = WXAPIFactory.createWXAPI(App.ctx, APP_ID);
		api.registerApp(APP_ID);
		setContentView(R.layout.activity_login);
		// startActivity(new Intent(getApplicationContext(),
		// MainActivity.class));

		// check();
		// IntentFilter filter=new IntentFilter("loginexit");
		// registerReceiver(emailBroadcastReceiver, filter);

		// 短信登录发送过来的广播
		IntentFilter filter1 = new IntentFilter(LOGINEXIT);
		registerReceiver(emailBroadcastReceiver, filter1);

		IntentFilter filter2 = new IntentFilter("AQLoginAQLogin");
		registerReceiver(emailBroadcasAQ, filter2);
		setStatusBarColor(R.color.home_blue);

	}

	// 检查是否登录过
	// public void check() {
	// if (IS_LOGINED) {
	// Intent intent = new Intent();
	// intent.setClass(LoginActivity.this, MainActivity.class);
	// startActivity(intent);
	// this.finish();
	// }
	// }

	@Override
	public void onClick(View v) {

		switch (v.getId()) {
		case R.id.login:

			phone = phoneedit.getText().toString();
			password = passwordedit.getText().toString();

			// 检查手机号
			Pattern p = Pattern
					.compile("^((13[0-9])|(17\\d)|(14\\d)|(15[^4,\\D])|(18[0-9]))\\d{8}$");
			Matcher m = p.matcher(phone);
			if (TextUtils.isEmpty(phone)) {

				Toast.makeText(App.ctx, "请输入手机号", 0).show();
			} else if (TextUtils.isEmpty(password)) {
				Toast.makeText(App.ctx, "请输入密码", 0).show();
			} else {

				SPUtils.put(App.ctx, null, SPContants.USERNAME, phone);
				SPUtils.put(App.ctx, null, SPContants.PASSWORD, password);
				login();
			}
			break;
		case R.id.wechat:
			welongin();
			break;
		case R.id.regist:
			Intent intent = new Intent(this, RegistActivity.class);
			startActivity(intent);
			break;
		// case R.id.smslogin:
		// Intent intent1 = new Intent(this, SmsLoginActivity.class);
		// startActivity(intent1);
		// break;
		case R.id.forgetpassword:
			Intent intent2 = new Intent(this, ResetPasswordActivity.class);
			startActivity(intent2);
			break;
		case R.id.btn_qqwechat:
			qqLogin();
			break;
		default:
			break;
		}

	}

	public void qqLogin() {
		mTencent = Tencent.createInstance(SPContants.TencentAppId,
				this.getApplicationContext());
		if (!mTencent.isSessionValid()) {
			mTencent.login(this, "all", this);
		}
	}

	public void onQQLonlogin() {
		MyJsonRequest.Builder<String> builder = new MyJsonRequest.Builder<String>()
				.apiVer("100").typeKey("BY_QQ_login").param("uid", "0")
				.param("access_token", "")
				.requestListener(new XRequestListener<String>() {

					@Override
					public void onResponse(String orderBean) {
						// onPullUpFinish(adapter, xlistview, orderBean);

					}
				}).errorListener(new XErrorListener() {

					@Override
					public void onErrorResponse(Exception exception, int code,
							String msg) {
						Toast.makeText(MyApplication.context, "反馈失败！", 0)
								.show();
					}
				});

		MyJsonRequest<String> request = builder.build();
		HttpRequest.getDefaultRequestQueue().add(request);
	}

	@Override
	protected void onActivityResult(int arg0, int arg1, Intent arg2) {
		// TODO Auto-generated method stub
		Tencent.onActivityResultData(arg0, arg1, arg2, this);

		if (arg0 == Constants.REQUEST_API) {
			if (arg0 == Constants.REQUEST_LOGIN) {
				Tencent.handleResultData(arg2, LoginActivity.this);
			}
		}
		if (arg0 == 11101 && arg0 == RESULT_OK) {
			// 处理返回的数据
			if (arg2 == null) {
				Toast.makeText(getApplicationContext(), "返回数据为空",
						Toast.LENGTH_LONG);
			} else {
				Tencent.handleResultData(arg2, this);
			}
		}
		super.onActivityResult(arg0, arg1, arg2);
	}

	// private void getAdImage() {
	// // TODO Auto-generated method stub
	// MyJsonRequest.Builder<AdBean> builder = new
	// MyJsonRequest.Builder<AdBean>()
	// .apiVer("100")
	// .typeKey("BY_Picture_getURL")
	// .param("position", "6121")
	// .requestListener(new XRequestListener<AdBean>() {
	//
	// @Override
	// public void onResponse(AdBean orderBean) {
	// // onPullUpFinish(adapter, xlistview, orderBean);
	// XImageLoader.load(orderBean.getImgUrl(), adImg);
	// }
	// }).errorListener(new XErrorListener() {
	//
	// @Override
	// public void onErrorResponse(Exception exception, int code,
	// String msg) {
	// Toast.makeText(DeviceActivity.this, exception+":"+code+":"+msg,
	// 0).show();
	// }
	// });
	//
	// MyJsonRequest<AdBean> request = builder.build();
	// HttpRequest.getDefaultRequestQueue().add(request);
	// }

	private void welongin() {
		// Toast.makeText(App.ctx, "haha", 0).show();
		// send oauth request
		// SendAuth.Req req = new SendAuth.Req();
		// req.scope = "snsapi_userinfo";
		// req.state = "wechat_sdk_demo_test";
		// api.sendReq(req);
		final SendAuth.Req req = new SendAuth.Req();
		req.scope = "snsapi_userinfo";
		req.state = "none";
		req.transaction = "login";
		api.sendReq(req);
	}

	public void login() {
		MyJsonRequest<PersonDataBean> request = new MyJsonRequest.Builder<PersonDataBean>()
				.apiVer("100")
				.typeKey("BY_User_login")
				.param("username",
						(String) SPUtils.get(App.ctx, null,
								SPContants.USERNAME, ""))
				.param("password",
						(String) SPUtils.get(App.ctx, null,
								SPContants.PASSWORD, ""))
				.requestListener(new XRequestListener<PersonDataBean>() {

					@Override
					public void onResponse(PersonDataBean response) {
						// TODO Auto-generated method stub
						DebugLog.v("result", response.toString());
						SPUtils.put(App.ctx, null, SPContants.WX_Openid,
								response.getWxopenid());
						SPUtils.put(App.ctx, null, SPContants.USERNAME,
								response.getUsername());
						SPUtils.put(App.ctx, null, SPContants.MOBILE,
								response.getMobile());
						SPUtils.put(App.ctx, null, SPContants.IS_LOGINED, true);
						SPUtils.put(App.ctx, null, SPContants.EMAIL,
								response.getEmail());
						SPUtils.put(App.ctx, null, SPContants.NICK,
								response.getNickname());
						SPUtils.put(App.ctx, null, SPContants.PASSWORD,
								response.getPassword());
						SPUtils.put(App.ctx, null, SPContants.USER_ID,
								response.getUid());
						SPUtils.put(App.ctx, null, SPContants.AVATAR_URL,
								response.getHead());
						SPUtils.put(App.ctx, null, SPContants.AQ_NUM,
								response.getAqCount());
						LoginActivity.this.finish();
						LoginController.setLoginState(new LoginedState());
						// 发送广播通知更改头像
						Intent intent2 = new Intent("changeavart");
						sendBroadcast(intent2);

						Intent intent3 = new Intent("sttringactivity");
						sendBroadcast(intent3);
					}
				}).errorListener(new XErrorListener() {

					@Override
					public void onErrorResponse(Exception exception, int code,
							String msg) {
						Toast.makeText(App.ctx, msg, 0).show();
					}
				}).build();
		HttpRequest.getDefaultRequestQueue().add(request);
	}

	BroadcastReceiver emailBroadcastReceiver = new BroadcastReceiver() {
		public void onReceive(Context context, Intent intent) {
			LoginActivity.this.finish();
		};
	};
	BroadcastReceiver emailBroadcasAQ = new BroadcastReceiver() {
		public void onReceive(Context context, Intent intent) {
			 code=intent.getStringExtra("weixinlofin");
			System.out.println("weixinlofin"+code);
			wechatLogin();
			
		};
	};

	protected void onDestroy() {
		super.onDestroy();
		unregisterReceiver(emailBroadcastReceiver);
	};

	@Override
	public void finish() {
		// TODO Auto-generated method stub
		super.finish();

		overridePendingTransition(0, R.anim.anim_falldown);
	}

	@Override
	public void onCancel() {
		// TODO Auto-generated method stub

		ByAlert.alert("QQ登录失败！");
	}

	@Override
	public void onComplete(Object arg0) {
		// TODO Auto-generated method stub
		// ByAlert.alert("onComplete" + arg0);
		System.out.println(arg0 + ">>>QQ登录回调");
		JSONObject jsonObject = null;

		try {
			jsonObject = new JSONObject(arg0.toString());
			openid = jsonObject.getString("openid");
			token = jsonObject.getString("access_token");

			System.out.println("liutiantain1" + token);
			System.out.println("xiaoliu" + openid);
			QQLoginGetUid(token, openid);
		} catch (JSONException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

	}

	public void QQLoginGetUid(final String token, final String openid) {
		MyJsonRequest<PersonDataBean> request = new MyJsonRequest.Builder<PersonDataBean>()
				.apiVer("100").typeKey("BY_QQ_login")
				.param("access_token", token)
				.requestListener(new XRequestListener<PersonDataBean>() {

					@Override
					public void onResponse(PersonDataBean response) {
						// TODO Auto-generated method stub
						System.out.println("BY_QQ_loginopenid" + token);
						QQBind(openid);

						DebugLog.v("result", response.toString());
						SPUtils.put(App.ctx, null, SPContants.WX_Openid,
								response.getWxopenid());
						SPUtils.put(App.ctx, null, SPContants.USERNAME,
								response.getUsername());
						SPUtils.put(App.ctx, null, SPContants.MOBILE,
								response.getMobile());
						SPUtils.put(App.ctx, null, SPContants.IS_LOGINED, true);
						SPUtils.put(App.ctx, null, SPContants.EMAIL,
								response.getEmail());
						SPUtils.put(App.ctx, null, SPContants.NICK,
								response.getNickname());
						SPUtils.put(App.ctx, null, SPContants.PASSWORD,
								response.getPassword());
						SPUtils.put(App.ctx, null, SPContants.USER_ID,
								response.getUid());
						SPUtils.put(App.ctx, null, SPContants.AVATAR_URL,
								response.getHead());
						// SPUtils.put(App.ctx, null, SPContants.AQ_NUM,
						// response.getAqCount());
						LoginActivity.this.finish();
						LoginController.setLoginState(new LoginedState());
						// 发送广播通知更改头像
						Intent intent2 = new Intent("changeavart");
						sendBroadcast(intent2);

						Intent intent3 = new Intent("sttringactivity");
						sendBroadcast(intent3);
					}
				}).errorListener(new XErrorListener() {

					@Override
					public void onErrorResponse(Exception exception, int code,
							String msg) {
						// Toast.makeText(App.ctx, "失败了吗", 0).show();

					}
				}).build();
		HttpRequest.getDefaultRequestQueue().add(request);
	}

	private void QQBind(final String openid) {
		// TODO Auto-generated method stub
		MyJsonRequest<String> request = new MyJsonRequest.Builder<String>()
				.apiVer("100")
				.typeKey("BY_QQ_bind")
				.param("openid", openid)
				.param("uid",
						(String) SPUtils.get(App.ctx, null, SPContants.USER_ID,
								""))
				.requestListener(new XRequestListener<String>() {

					@Override
					public void onResponse(String response) {
						// TODO Auto-generated method stub
						System.out.println("BY_QQ_loginopenid" + response);
						// Toast.makeText(App.ctx, "成功", 0).show();
						System.out.println("成功了吗" + response);
						System.out.println("xiaoliu2" + openid);
						finish();

					}
				}).errorListener(new XErrorListener() {

					@Override
					public void onErrorResponse(Exception exception, int code,
							String msg) {
						// Toast.makeText(App.ctx, "失败", 0).show();
					}
				}).build();
		HttpRequest.getDefaultRequestQueue().add(request);
	}

	@Override
	public void onError(UiError arg0) {
		// TODO Auto-generated method stub
		System.out.println("Token" + arg0.errorDetail);

	}
	private void wechatLogin() {
		MyJsonRequest<PersonDataBean> request = new MyJsonRequest.Builder<PersonDataBean>()
				.apiVer("100").typeKey("BY_Weixin2_login").param("code", code)
				.requestListener(new XRequestListener<PersonDataBean>() {

					public void onResponse(PersonDataBean response) {
						DebugLog.v("result", response.toString());
						SPUtils.put(App.ctx, null, SPContants.WX_Openid,
								response.getWxopenid());
						SPUtils.put(App.ctx, null, SPContants.USERNAME,
								response.getUsername());
						SPUtils.put(App.ctx, null, SPContants.MOBILE,
								response.getMobile());
						SPUtils.put(App.ctx, null, SPContants.IS_LOGINED, true);
						SPUtils.put(App.ctx, null, SPContants.EMAIL,
								response.getEmail());
						SPUtils.put(App.ctx, null, SPContants.NICK,
								response.getNickname());
						SPUtils.put(App.ctx, null, SPContants.PASSWORD,
								response.getPassword());
						SPUtils.put(App.ctx, null, SPContants.USER_ID,
								response.getUid());
						SPUtils.put(App.ctx, null, SPContants.AVATAR_URL,
								response.getHead());
						SPUtils.put(App.ctx, null, SPContants.AQ_NUM,
								response.getAqCount());
						LoginActivity.this.finish();
						System.out.println("shixiansonghuiqiao"+code);
						LoginController.setLoginState(new LoginedState());
						// 发送广播通知更改头像
						
						Intent intent2 = new Intent("changeavart");
						sendBroadcast(intent2);

						Intent intent3 = new Intent("sttringactivity");
						sendBroadcast(intent3);
						LoginController.setLoginState(new LoginedState());
						// 手机认证
						if (response.getPhoneValidate().equals("1")) {

							SPUtils.put(App.ctx, null,
									SPContants.USERNAME, response.getUsername());
							SPUtils.put(App.ctx, null,
									SPContants.IS_LOGINED, true);
							SPUtils.put(App.ctx, null,
									SPContants.EMAIL, response.getEmail());
							SPUtils.put(App.ctx, null,
									SPContants.NICK, response.getNickname());

							SPUtils.put(App.ctx, null,
									SPContants.PASSWORD, response.getPassword());
							SPUtils.put(App.ctx, null,
									SPContants.MOBILE, response.getMobile());
							SPUtils.put(App.ctx, null,
									SPContants.WX_Openid,
									response.getWxopenid());
							// �����û�Id
							// Toast.makeText(App.ctx, response.getUid(),
							// 0).show();
							SPUtils.put(App.ctx, null,
									SPContants.USER_ID, response.getUid());
							// �����û�ͷ��
							SPUtils.put(App.ctx, null,
									SPContants.AVATAR_URL, response.getHead());
							LoginController.setLoginState(new LoginedState());
							Intent intent1 = new Intent("changeavart");
							sendBroadcast(intent1);
							LoginActivity.this.finish();
							

						} else if (response.getPhoneValidate().equals("0")) {


						}
						LoginActivity.this.finish();
						
					}
				}).errorListener(new XErrorListener() {

					@Override
					public void onErrorResponse(Exception exception, int code,
							String msg) {
						if (exception instanceof CodeErrorException) {
							Toast.makeText(App.ctx, msg, 0)
									.show();
						} else {
							Toast.makeText(App.ctx,
									exception.toString(), 0).show();
						}

					}
				}).build();
		HttpRequest.getDefaultRequestQueue().add(request);
	}
	
}
